import matplotlib.pyplot as plt
import numpy as np
from sys import argv
import os
import re


class StatPlot(object):
  def __init__(self, fname):
    # f = open("statistics.txt","r")
    f = open(fname,"r")
    w = f.readlines()
    f.close()
    self.agents = {}
    for line in w:
      tm, _, rest     = line.partition("\t")
      agent, _, rest  = rest.partition("\t")
      speed, _, qsize = rest.partition("\t")
      if speed == '':
        speed = 1
      try:
        tmp = self.agents[agent]
        tmp.append( (float(tm), float(speed), int(qsize) ) )
        self.agents[agent] = tmp
      except KeyError, e:
        self.agents[agent] = [(float(tm), float(speed), int(qsize) )]
    for agent in self.agents:
      self.agents[agent].sort()

  def plot_qsize(self):
    ax = plt.subplot(111)
    for agent in self.agents:
      tmp = self.agents[agent]
      xs  = [i[0] for i in tmp]
      ys  = [i[2] for i in tmp]
      ax.plot(xs, ys)
    plt.show()

  def plot_load(self):
    ax = plt.subplot(111)
    for agent in self.agents:
      tmp = self.agents[agent]
      s  = [ (i[0], i[2]/i[1]) for i in tmp if i[1] != 0]
      xs = [i[0] for i in s]
      ys = [i[1] for i in s]
      ax.plot(xs, ys)
    plt.show()


  def compute_std_deviance(self):
    #wartosci obciazenia w kolejnych punktach czasowych
    #slownik czas -> lista obciazen
    self.loads = {}
    for agent in self.agents:
      tmp = self.agents[agent]
      for tm, speed, qsize in tmp:
          self.loads[tm] = self.loads.get(tm,[]) + [qsize/speed]
    self.loads  = list(self.loads.values())
    avg_std_dev = np.average( [ np.std(l) for l in self.loads ] )
    return avg_std_dev

  def compute_avg_load(self):
    '''Liczy srednia roznice miedzy najwiekszym, a naj,mniejszym obciazeniam'''
    #wartosci obciazenia w kolejnych punktach czasowych
    #slownik czas -> lista obciazen
    self.loads = {}
    for agent in self.agents:
      tmp = self.agents[agent]
      for tm, speed, qsize in tmp:
          self.loads[tm] = self.loads.get(tm,[]) + [qsize/speed]
    self.loads  = list(self.loads.values())
    avg_std_dev = np.average( [ np.max(l) - np.min(l) for l in self.loads ] )
    return avg_std_dev


  def compute_messages(self, folderpath):
    '''Zlicza liczbe wyslanych i odebranych wiadomosci'''
    send_msgs = 0
    rcvd_msgs = 0
    send_urls = 0
    rcvd_urls = 0
    for i,j,k in os.walk(folderpath):
      for fl in k:
          if fl.startswith("stat_rcvd_msgs"):
            f = open( os.path.join(folderpath, fl) )
            rcvd_msgs += int(f.read())
            f.close()
          elif fl.startswith("stat_rcvd_urls"):
            f = open( os.path.join(folderpath, fl) )
            rcvd_urls += int(f.read())
            f.close()
          elif fl.startswith("stat_sent_msgs"):
            f = open( os.path.join(folderpath, fl) )
            send_msgs += int(f.read())
            f.close()
          elif fl.startswith("stat_sent_urls"):
            f = open( os.path.join(folderpath, fl) )
            send_urls += int(f.read())
            f.close()
      break
    return (send_msgs, rcvd_msgs, send_urls, rcvd_urls)



if __name__ == '__main__':
  s = StatPlot(argv[1])
##  s.plot_qsize()
  print s.compute_std_deviance()
  print s.compute_avg_load()
  s.plot_load()
##  print s.compute_messages("_ok_centralLB_1_stats")
